import { Request, Response } from 'express';
import svgCaptcha from 'svg-captcha';
import { CustomSession } from '../../types/auth';

export type CaptchaRequest = Request & {
    session: CustomSession;
};

export function getCaptcha(req: CaptchaRequest, res: Response): Response | void {
    const captcha = svgCaptcha.create({
        size: 4,// 验证码长度
        noise: 2,// 干扰线条数
        color: true,// 验证码字体颜色
        background: '#f0f0f0',// 验证码图片背景颜色
        ignoreChars: '0oO1ilI', // 验证码字符中排除 0o1i
        inverse:false,
        width: 150,
        height: 50,
        fontSize: 50
    });
    captcha.data = captcha.data.replace(/fill="#(?!(?:f0f0f0))([A-Fa-f0-9]{6})"/g, 'fill="#FF0000"');
    if (!req.session) {
        return res.status(500).json({
            success: false,
            message: 'Session 未初始化'
        });
    }

    req.session.captcha = captcha.text;
    
    req.session.cookie.httpOnly = true;
    req.session.cookie.secure = process.env.NODE_ENV === 'production';
    req.session.cookie.sameSite = 'strict';
    req.session.cookie.maxAge = 5 * 60 * 1000; // 5分钟过期
    
    req.session.save((err) => {
        if (err) {
            return res.status(500).json({
                success: false,
                message: '验证码保存失败'
            });
        }
        
        res.type('svg');
        res.status(200).send(captcha.data);
    });
} 